<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_expressadjust extends desktop_controller{

    var $workground = 'wms_ctl_admin_expressadjust';
    var $pagelimit = 10;
    var $stocknotice_model ;
    public function __construct($app)
    {
        parent::__construct($app);
        $this->member_model = $this->app->model('expressadjust');
        header("cache-control: no-store, no-cache, must-revalidate");
    }
    //备货通知单首页
   function index()
   {

        $filter=array();
       // $is_super = $this->user->is_super();
       // if($is_super != 1){
       //     $filter['operator'] = $this->user->get_name();
       // }

        $params = array(
            'title' => '快递费调整单',
            'actions' => array(
                'new' => array(
                    'label' => '新建',
                    'href' => 'index.php?app=wms&ctl=admin_expressadjust&act=add_expressadjust',
                        'target' => '_blank',
                ),
                'confirm' => array(
                    'label' => '确认',
                    'submit' => 'index.php?app=wms&ctl=admin_expressadjust&act=doConfirm',
                ),
                'undoconfirm' => array(
                    'label' => '取消确认',
                    'submit' => 'index.php?app=wms&ctl=admin_expressadjust&act=doundoConfirm',
                ),
                'delete' => array(
                    'label' => '删除',
                    'submit' => 'index.php?app=wms&ctl=admin_expressadjust&act=doDelete',
                ),
            ),
            'base_filter' => $filter,
            //'base_filter' => '',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => true ,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,

            'orderBy' => 'create_time desc',
        );
        $this->finder('wms_mdl_expressadjust', $params);

    }
    //添加备货
    function add_expressadjust()
    {


        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['expressadjust']['operator'] = $operator;
        $this->pagedata['expressadjust']['expressadjust_bn']=$this->autocreatebn();

        $this->singlepage('admin/expressadjust/expressadjust_add.html');
    }
    function autocreatebn()
    {
        $bn='';
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $time_begin= mktime(0,0,0,$m,$d,$y);
        $time_end= mktime(23,59,59,$m,$d,$y);
        $delivery_model = $this->app->model('expressadjust');
        $filter['create_time|between'] = array($time_begin, $time_end);
        $delivery= $delivery_model->getList('expressadjust_bn',$filter,0,1,'create_time desc');
        if($delivery[0]['expressadjust_bn']=='')
        {
            $bn ='EA'.date('Ymd',time()).'01';
        }
        else
        {
            $bn=substr($delivery[0]['expressadjust_bn'] , 10 , 2);
            $num=intval($bn)+1;
            if($num<=9)
            {
                $bn ='EA'.date('Ymd',time()).'0'.$num;
            }else
            {
                $bn ='EA'.date('Ymd',time()).$num;
            }
        }
        return $bn;
    }


    /**
     * 基础物料列表弹窗数据获取方法
     *
     * @param Void
     * @return String
     */
    function finddelivery($supplier_id=null)
    {

        $base_filter['is_ship'] = 'true';
        $base_filter['status'] = 3;
        $base_filter['print_status'] = 4;
        $base_filter['process_status'] = 7;
        $base_filter['delivery_time|than'] = 1527696000;
        $base_filter['deliverytype'] = array('pickup','delivery','auto','batch','single');
        $base_filter['is_form'] = 'true';
        if(!$_POST['shop_id']){
            $base_filter['shop_id'] = $this->shopIds;
        }else{
            $base_filter['shop_id'] = $_POST['shop_id'];
        }
        $params = array(
                'title'=>'发货单',
                'use_buildin_new_dialog' => false,
                'use_buildin_set_tag'=>false,
                'use_buildin_recycle'=>false,
                'use_buildin_export'=>false,
                'use_buildin_import'=>false,
                'use_buildin_filter'=>true,
                'base_filter' => $base_filter,
        );
        $this->finder('wms_mdl_delivery', $params);
    }

    function getdeliverys()
    {
        //$basicMaterialSelect    = kernel::single('delivery_select');#基础物料 ExBOY
        //$basicMaterialBarcode    = kernel::single('material_basic_material_barcode');#条形码 ExBOY
       
        $pro_id = $_POST['product_id'];
        $sql='SELECT delivery_bn,lmfee,delivery_cost_actual,w.delivery_id,f.shop_id,outer_delivery_bn,bnscontent,net_weight,items.bn,items.number,f.`name` shop_name,items.item_id from sdb_wms_delivery w
            inner join sdb_wms_delivery_items items on w.delivery_id=items.delivery_id
            inner join sdb_ome_shop f on w.shop_id=f.shop_id
            where w.delivery_id in(\''.implode('\',\'', $pro_id).'\')';
        $db=kernel::database();
        $delivery=$db->select($sql);
        if (!empty($delivery))
        {
            foreach ($delivery as $k => $item)
            {
                $item['shop_id']=$item['shop_id'];
                $item['shop_name']=$item['shop_name'];
                $item['product_id']=$k;//$item['delivery_id'];
                $item['delivery_id']=$item['delivery_id'];
                $item['bnscontent']=$item['bn'];
                $item['item_id']=$item['item_id'];
                if(empty($item['lmfee']))
                {
                    $item['lmfee']=0.000;
                    $item['almfee']=0.000;   
                }else{
                    $item['lmfee']=$item['lmfee'];
                    $item['almfee']=$item['lmfee'];   
                }
                if(empty($item['delivery_cost_actual']))
                {
                    $item['delivery_cost_actual']=0.000;
                    $item['adelivery_cost_actual']=0.000; 
                }else{
                    
                    $item['delivery_cost_actual']=$item['delivery_cost_actual'];
                    $item['adelivery_cost_actual']=$item['delivery_cost_actual'];
                }
                if(empty($item['number']))
                {
                    $item['number']=0;
                    $item['anumber']=0; 
                }else{
                    
                    $item['number']=$item['number'];
                    $item['anumber']=$item['number'];
                }
                if(empty($item['net_weight']))
                {
                    $item['net_weight']=0;
                    $item['anet_weight']=0; 
                }else{
                    
                    $item['net_weight']=$item['net_weight'];
                    $item['anet_weight']=$item['net_weight'];
                }

                $item['delivery_bn']=$item['delivery_bn'];
                $rows[]= $item;
            }
        }
        echo "window.autocompleter_json=".json_encode($rows);
    }
    function getdeliveryitems($delivery_id,$item_id)
    {
        $sql='SELECT delivery_bn,lmfee,delivery_cost_actual,w.delivery_id,f.shop_id,outer_delivery_bn,bnscontent,net_weight,items.bn,items.number,f.`name` shop_name,items.item_id from sdb_wms_delivery w
            inner join sdb_wms_delivery_items items on w.delivery_id=items.delivery_id
            inner join sdb_ome_shop f on w.shop_id=f.shop_id
            where w.delivery_id='.$delivery_id.' and items.item_id='.$item_id;
        $db=kernel::database();
        $delivery=$db->select($sql);
        return $delivery;
    }
    //保存备货通知单
    function doSave()
    {
        $this->begin();
        $expressadjust_model = $this->app->model('expressadjust');
        $expressadjustDeil_model = $this->app->model('expressadjust_line');
        $delivery_ID = $_POST['delivery_ID'];
        $memo = $_POST['memo'];
        $id=$_POST['id'];
        $operator = $_POST['operator'];
        if(empty($id)){
            $expressadjust_id = $expressadjust_model ->getList('id',array('expressadjust_bn'=>$_POST['purchase_name']));
            if ($expressadjust_id) 
            {
                $this->end(false, '存在多人同时操作，请稍后重试');
            }
            $arr_order='';
            $arr_order['expressadjust']['expressadjust_bn']=$this->autocreatebn();//$_POST['purchase_name'];
            $arr_order['expressadjust']['remark']=$_POST['memo'];
            $arr_order['expressadjust']['operator']=$_POST['operator'];
            $arr_order['expressadjust']['create_time']=time();
            $res = $expressadjust_model->insert($arr_order['expressadjust']);

        }else
        {
            $res=$id;
            $params=array(
                'id'=>$res,
                'remark'=>$_POST['memo'],
            );
            $expressadjust_model->save($params);
            kernel::database()->exec("delete from sdb_wms_expressadjust_line  where  expressadjust_id in(" . $id . ");");
        } 
        $orders_obj = $this->app->model('delivery');
        $shopMdl = app::get('ome')->model('shop');
        foreach ($delivery_ID as $key => $value)
        {
            $orders=$this->getdeliveryitems($value['delivery_id'],$value['item_id']);
            if(!empty($orders))
            {
                $arr_line='';
                $arr_line['adline']['delivery_bn']=$orders[0]['delivery_bn'];
                $arr_line['adline']['shop_id']=$orders[0]['shop_id'];
                $arr_line['adline']['shop_name']=$orders[0]['shop_name'];
                $arr_line['adline']['bnscontent']=$value['bnscontent'];
                $arr_line['adline']['net_weight']=$orders[0]['net_weight'];
                $arr_line['adline']['delivery_id']=$value['delivery_id'];
                $arr_line['adline']['item_id']=$value['item_id'];
                $arr_line['adline']['expressadjust_id']=$res;
                if(empty($orders[0]['lmfee']))
                {
                    $arr_line['adline']['lmfee']=0.00;
                }else{
                    $arr_line['adline']['lmfee']=$orders[0]['lmfee'];
                }
                if(empty($orders[0]['delivery_cost_actual']))
                {
                    $arr_line['adline']['delivery_cost_actual']=0.00;
                }else{
                    
                    $arr_line['adline']['delivery_cost_actual']=$orders[0]['delivery_cost_actual'];
                }
                if(empty($orders[0]['number']))
                {
                    $arr_line['adline']['number']=-0.00;
                }else{
                    
                    $arr_line['adline']['number']=$orders[0]['number'];
                }
                if(empty($value['almfee']))
                {
                    $arr_line['adline']['almfee']=-0.00;
                }else{
                    
                    $arr_line['adline']['almfee']=$value['almfee'];
                }
                if(empty($value['adelivery_cost_actual']))
                {
                    $arr_line['adline']['adelivery_cost_actual']=-0.00;
                }else{
                    
                    $arr_line['adline']['adelivery_cost_actual']=$value['adelivery_cost_actual'];
                }
                if(empty($value['anet_weight']))
                {
                    $arr_line['adline']['anet_weight']=-0.00;
                }else{
                    
                    $arr_line['adline']['anet_weight']=$value['anet_weight'];
                }
                if(empty($value['anumber']))
                {
                    $arr_line['adline']['anumber']=-0.00;
                }else{
                    
                    $arr_line['adline']['anumber']=$value['anumber'];
                }
                $expressadjustDeil_model->insert($arr_line['adline']);
            }
        }
        $this->end(true, '已完成');
    }
    //提交动作
    function doConfirm()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_expressadjust&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();
        $db=kernel::database();
        $expressadjustMdl = $this->app->model('expressadjust_line');
        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key_o => $order) 
            {
                $value = $order['id']; 
                //确认后自动生成开立的审批单

                $expressadjustData = $this->getselectall($value);
                foreach ($expressadjustData as $k => $v) 
                {
                    if(empty($v['adelivery_cost_actual']))
                    {
                        $actual=0;
                    }else{
                        $actual=$v['adelivery_cost_actual'];
                    }
                    if(empty($v['almfee']))
                    {
                        $almfee=0;
                    }else{
                        $almfee=$v['almfee'];
                    }
                    if(empty($v['anumber']))
                    {
                        $anumber=0;
                    }else{
                        $anumber=$v['anumber'];
                    }
                    if(empty($v['anet_weight']))
                    {
                        $anet_weight=0;
                    }else{
                        $anet_weight=$v['anet_weight'];
                    }
                    $this->updatedelivery($almfee,$actual,$anumber,$anet_weight,$v['delivery_id'],$v['wms_delivery_id'],$v['item_id']);
                }
                //$db->exec("update sdb_wms_delivery set lmfee=0,delivery_cost_actual=0,last_modify='".time()."' where  delivery_id in(".$id.")");
                $db->exec("update sdb_wms_expressadjust set status='confirmed',last_modify='".time()."' where id in(".$value.");");
            }
        }else
        {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {
                $expressadjustData = $this->getselectall($value);
                foreach ($expressadjustData as $k => $v) 
                {
                    if(empty($v['adelivery_cost_actual']))
                    {
                        $actual=0;
                    }else{
                        $actual=$v['adelivery_cost_actual'];
                    }
                    if(empty($v['almfee']))
                    {
                        $almfee=0;
                    }else{
                        $almfee=$v['almfee'];
                    }
                    if(empty($v['anumber']))
                    {
                        $anumber=0;
                    }else{
                        $anumber=$v['anumber'];
                    }
                    if(empty($v['anet_weight']))
                    {
                        $anet_weight=0;
                    }else{
                        $anet_weight=$v['anet_weight'];
                    }
                    $this->updatedelivery($almfee,$actual,$anumber,$anet_weight,$v['delivery_id'],$v['wms_delivery_id'],$v['item_id']);
                }
                //$db->exec("update sdb_wms_delivery set lmfee=0,delivery_cost_actual=0,last_modify='".time()."' where  delivery_id in(".$id.")");
                $db->exec("update sdb_wms_expressadjust set status='confirmed',last_modify='".time()."' where id in(".$value.");");
            }
        }      //
        $this->end(true, '已完成');
    }
    function updatedelivery($lmfee,$actual,$anumber,$anet_weight,$delivery_id,$wms_delivery_id,$item_id)
    {
        $db = kernel::database();
        $db->exec("update sdb_ome_delivery set lmfee=$lmfee,delivery_cost_actual=$actual,net_weight=$anet_weight,delivery_cost_expect=$actual,last_modified=".time()." where delivery_id=".$delivery_id) ;
        $db->exec("update sdb_wms_delivery set lmfee=$lmfee,delivery_cost_actual=$actual,net_weight=$anet_weight,delivery_cost_expect=$actual,last_modified=".time()." where delivery_id=".$wms_delivery_id);
        $db->exec("update sdb_wms_delivery_items set flatfeeprice=$actual,number=$anumber where delivery_id=".$wms_delivery_id." and item_id=".$item_id); 
    }
    function getselectall($expressadjust_id)
    {
        $sql="SELECT w.delivery_id as wms_delivery_id,o.delivery_id,li.adelivery_cost_actual,li.anet_weight,li.almfee,li.lmfee,li.delivery_cost_actual,li.number,li.anumber,li.item_id,li.net_weight
            FROM sdb_wms_expressadjust_line li 
            inner join sdb_wms_delivery as w on li.delivery_id=w.delivery_id
            inner join sdb_ome_delivery as o on w.outer_delivery_bn=o.delivery_bn 
            WHERE li.expressadjust_id=".$expressadjust_id;
        $db = kernel::database();
        return $db->select($sql);
    }
    //取消确认动作
    function doundoConfirm()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_expressadjust&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $db = kernel::database();
        $expressadjustMdl = $this->app->model('expressadjust');
        $expressadjustMdline = $this->app->model('expressadjust_line');

        if ($order_info['isSelectedAll']=='_ALL_') {
            foreach ($orders as $key_o => $order) {
                $value = $order['id'];
                $orders = $expressadjustMdl->getList('*', array('id'=>$value), 0, 1);
                if($order['status']=='confirmed')
                {
                    $expressadjustData = $this->getselectall($value);
                    foreach ($expressadjustData as $k => $v) 
                    {
                        if(empty($v['delivery_cost_actual']))
                        {
                            $actual=0;
                        }else{
                            $actual=$v['delivery_cost_actual'];
                        }
                        if(empty($v['lmfee']))
                        {
                            $lmfee=0;
                        }else{
                            $lmfee=$v['lmfee'];
                        }
                        if(empty($v['number']))
                        {
                            $number=0;
                        }else{
                            $number=$v['number'];
                        }

                        if(empty($v['anet_weight']))
                        {
                            $anet_weight=0;
                        }else{
                            $anet_weight=$v['anet_weight'];
                        }
                        $this->updatedelivery($lmfee,$actual,$number,$anet_weight,$v['delivery_id'],$v['wms_delivery_id'],$v['item_id']);
                    }

                    $db->exec("update sdb_wms_expressadjust set status = 'unconfirmed',last_modify='".time()."' where  id in(".$value.")");
                 
                }else{

                    $this->end(false, '状态异常，取消失败！');           
                }
            }
        }else
        {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {
                $orders = $expressadjustMdl->getList('*', array('id'=>$value), 0, 1);

                if($orders[0]['status']=='confirmed')
                {  
                    $expressadjustData = $this->getselectall($value);
                    foreach ($expressadjustData as $k => $v) 
                    {
                        if(empty($v['delivery_cost_actual']))
                        {
                            $actual=0;
                        }else{
                            $actual=$v['delivery_cost_actual'];
                        }
                        if(empty($v['lmfee']))
                        {
                            $lmfee=0;
                        }else{
                            $lmfee=$v['lmfee'];
                        }
                        if(empty($v['number']))
                        {
                            $number=0;
                        }else{
                            $number=$v['number'];
                        }

                        if(empty($v['anet_weight']))
                        {
                            $anet_weight=0;
                        }else{
                            $anet_weight=$v['anet_weight'];
                        }
                        $this->updatedelivery($lmfee,$actual,$number,$anet_weight,$v['delivery_id'],$v['wms_delivery_id'],$v['item_id']);
                    }
                    $db->exec("update sdb_wms_expressadjust set status = 'unconfirmed',last_modify='".time()."' where id in(".$value.")");
                }else{

                    $this->end(false, '状态异常，取消失败！');           
                }
            }
        }
        $this->end(true, '已完成');
    }
    //确认动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_expressadjust&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $expressadjust_model = $this->app->model('expressadjust');
        $orders_obj = $this->app->model('delivery');

        if ($order_info['isSelectedAll']=='_ALL_') {
            $orders = $expressadjust_model->getList('*', array(), 0, -1);
            foreach ($orders as $key => $order) {
                $value = $order['id'];
                if ($order['status'] == 'unconfirmed') 
                {
                    $expressadjust_model->db->exec("delete from sdb_wms_expressadjust_line where expressadjust_id in(".$value . ");");
                    $expressadjust_model->db->exec("delete from sdb_wms_expressadjust  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '备货单号【' . $order['expressadjust_bn'] . '】状态已提交，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) {
                $orders = $expressadjust_model->getList('*', array('id' => $value), 0, 1);

                if ($orders[0]['status'] == 'unconfirmed') 
                {
                    $expressadjust_model->db->exec("delete from sdb_wms_expressadjust_line where expressadjust_id in(" . $value . ");");
                    $expressadjust_model->db->exec("delete from sdb_wms_expressadjust where id in(" . $value . ");");
                } else {
                    $this->end(false, '备货单号【' . $orders[0]['expressadjust_bn'] . '】状态已提交，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }
    function editexpressadjust()
    {
        $expressadjust_model = $this->app->model('expressadjust');
        $expressadjust_datas = $expressadjust_model->getList('*', array('id'=>$_GET['id']), 0, -1);
        $expressadjust_datas[0]['memo']=$expressadjust_datas[0]['remark'];
        $this->pagedata['expressadjust'] = $expressadjust_datas[0];
        $this->singlepage('admin/expressadjust/expressadjust_edit.html');
    }

    function getEditProducts($po_id){
        if ($po_id == ''){
            $po_id = $_POST['p[0]'];
        }
        $sql="SELECT e.delivery_bn,os.order_bn,li.* 
            from sdb_wms_delivery e 
            inner join sdb_ome_shop f on e.shop_id = f.shop_id 
            inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn ) 
            inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id ) 
            inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id) 
            inner join sdb_wms_expressadjust_line li on e.delivery_id=li.delivery_id 
            where li.expressadjust_id=".$po_id;

        $db=kernel::database();
        $basicMaterialInfo=$db->select($sql);  

        foreach ($basicMaterialInfo as $key => $value) {
            $row['product_id']=$key;
            $row['delivery_id']=$value['delivery_id'];
            $row['delivery_bn']=$value['delivery_bn'];
            $row['shop_id']=$value['shop_id'];
            $row['almfee']=$value['almfee'];
            $row['adelivery_cost_actual']=$value['adelivery_cost_actual'];
            $row['lmfee']=$value['lmfee'];
            $row['delivery_cost_actual']=$value['delivery_cost_actual'];
            $row['shop_id']=$value['shop_id'];
            $row['shop_name']=$value['shop_name'];
            $row['net_weight']=$value['net_weight'];
            $row['anet_weight']=$value['anet_weight'];
            $row['bnscontent']=$value['bnscontent'];
            $row['item_id']=$value['item_id'];
            $row['anumber']=$value['anumber'];
            $row['number']=$value['number'];
            $items[]=$row;
        }
        echo json_encode($items);
    }

}
